﻿using System;

using enyo;

namespace com.RexToy
{
    public abstract class ConverterView : enyo.Control
    {
        protected string baseUnit;
        protected object fomular;
        protected string[] units;

        public void Calc(string curUnit, double curVal)
        {
            var baseVal = curVal;
            if (curUnit != this.baseUnit)
            {
                var expr = this.fomular[curUnit + "->" + this.baseUnit];
                string stmt = "var " + curUnit + "=" + curVal + ";" + expr;
                this.Log("calc base value:[" + stmt + "]");
                baseVal = (double)System.Global.Eval(stmt);
            }

            this.Log("baseVal = " + baseVal);

            foreach (var toCalcUnit in this.units)
            {
                if (toCalcUnit != curUnit)
                {
                    var expr = this.fomular[this.baseUnit + "->" + toCalcUnit];
                    string stmt = "var " + this.baseUnit + "=" + baseVal + ";" + expr;
                    this.Log("calc " + toCalcUnit + "[" + stmt + "]");
                    var toCalcVal = this.RoundIt((double)System.Global.Eval(stmt), 4);
                    enyo.Input input = this._[toCalcUnit] as enyo.Input;
                    input.SetValue(toCalcVal.ToString());
                }
            }
        }

        public void ShowAlert()
        {
            var pop = this._["Popup"] as Popup;
            if (pop == null)
            {
                pop = this.CreateComponent(new
                {
                    kind = ControlKind.Popup,
                    name = "Popup",
                    components = new object[]{
                        new { content= enyo.Global._L("Please enter a number.")}                                                               }
                }) as Popup;
            }
            pop.OpenAtCenter();
        }

        public bool IsNumber(enyo.Input ctrl)
        {
            var v = ctrl.GetValue().Trim();
            if (v == "" || System.Global.IsNaN(v))
            {
                this.ShowAlert();
                return false;
            }
            return true;
        }

        public double GetNumber(enyo.Input ctrl)
        {
            return System.Global.Number(ctrl.GetValue());
        }

        public double RoundIt(double val, int precise)
        {
            var factor = Math.Pow(10, precise);
            return Math.Round(val * factor) / factor;
        }

        public void blur(object sender)
        {
            var input = sender as Input;
            if (this.IsNumber(input))
            {
                this.Calc(input.name, this.GetNumber(input));
            }
        }
    }
}
